package com.liujit.standard.basis.admin.config.filter;

import cn.hutool.core.convert.Convert;
import com.liujit.standard.basis.admin.util.ApiUtil;
import com.liujit.standard.basis.core.domain.result.UserInfo;
import com.liujit.standard.basis.core.service.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @description: sessionToken续期 过滤器配置
 * @author: liujun
 * @create: 2021/3/24 6:38 下午
 **/
@Slf4j
@Order(1)
@WebFilter(filterName = "sessionTokenFilter", urlPatterns = "/*")
public class SessionTokenFilter implements Filter {

    @Resource
    private RedisService redisService;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        UserInfo user = ApiUtil.getSysUser();
        if (user != null) {
            String k = Convert.toStr(user.getId());
            String token = Convert.toStr(redisService.get(k));
            if (token != null) {
                log.info("登录续期");
                redisService.set(k, token, 30L, TimeUnit.MINUTES);
                redisService.set(token, user, 30L, TimeUnit.MINUTES);
            }
        }
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        // 请求耗时
        long start = System.currentTimeMillis();
        filterChain.doFilter(req, resp);
        log.info("{}请求耗时：{}", req.getRequestURI(), (System.currentTimeMillis() - start));
    }
}
